<template>
  <div class="cars-container">
    <div class="page-header">
      <h1>车辆展示</h1>
      <p>浏览我们的精选二手车，找到您的理想座驾</p>
    </div>

    <!-- 筛选和搜索区域 -->
    <div class="filter-section">
      <div class="search-box">
        <input type="text" v-model="filters.keyword" placeholder="输入品牌、型号或关键词">
        <button @click="searchCars">搜索</button>
      </div>
      
      <div class="filters">
        <div class="filter-group">
          <label>品牌</label>
          <select v-model="filters.brand">
            <option value="">全部品牌</option>
            <option value="宝马">宝马</option>
            <option value="奔驰">奔驰</option>
            <option value="奥迪">奥迪</option>
            <option value="特斯拉">特斯拉</option>
            <option value="丰田">丰田</option>
            <option value="本田">本田</option>
            <option value="大众">大众</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>价格区间</label>
          <select v-model="filters.priceRange">
            <option value="">全部价格</option>
            <option value="0-10">10万以下</option>
            <option value="10-15">10-15万</option>
            <option value="15-20">15-20万</option>
            <option value="20-30">20-30万</option>
            <option value="30-50">30-50万</option>
            <option value="50-">50万以上</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>车型</label>
          <select v-model="filters.carType">
            <option value="">全部车型</option>
            <option value="sedan">轿车</option>
            <option value="suv">SUV</option>
            <option value="new-energy">新能源</option>
            <option value="luxury">豪华车</option>
          </select>
        </div>
        
        <div class="filter-group">
          <label>车龄</label>
          <select v-model="filters.age">
            <option value="">全部车龄</option>
            <option value="0-1">1年内</option>
            <option value="1-3">1-3年</option>
            <option value="3-5">3-5年</option>
            <option value="5-8">5-8年</option>
            <option value="8-">8年以上</option>
          </select>
        </div>
        
        <button class="reset-btn" @click="resetFilters">重置筛选</button>
      </div>
    </div>

    <!-- 排序选项 -->
    <div class="sort-section">
      <span>排序方式：</span>
      <div class="sort-options">
        <button 
          :class="{ active: sortOption === 'default' }" 
          @click="setSortOption('default')"
        >默认</button>
        <button 
          :class="{ active: sortOption === 'price-asc' }" 
          @click="setSortOption('price-asc')"
        >价格 ↑</button>
        <button 
          :class="{ active: sortOption === 'price-desc' }" 
          @click="setSortOption('price-desc')"
        >价格 ↓</button>
        <button 
          :class="{ active: sortOption === 'year-desc' }" 
          @click="setSortOption('year-desc')"
        >车龄 ↑</button>
        <button 
          :class="{ active: sortOption === 'mileage-asc' }" 
          @click="setSortOption('mileage-asc')"
        >里程 ↑</button>
      </div>
      
      <div class="view-switch">
        <button :class="{ active: viewMode === 'grid' }" @click="viewMode = 'grid'">
          <i class="el-icon-s-grid"></i>
        </button>
        <button :class="{ active: viewMode === 'list' }" @click="viewMode = 'list'">
          <i class="el-icon-menu"></i>
        </button>
      </div>
    </div>

    <!-- 搜索结果统计 -->
    <div class="results-count">
      找到 <span>{{ filteredCars.length }}</span> 款符合条件的车辆
    </div>

    <!-- 车辆展示区域 -->
    <div :class="['car-display', `view-${viewMode}`]">
      <div class="car-card" v-for="car in filteredCars" :key="car.id">
        <div class="car-image">
          <img :src="car.imgUrl" :alt="car.title">
          <span class="price">{{ car.sellingPrice }}万</span>
        </div>
        <div class="car-info">
          <h3>{{ car.title }}</h3>
          <p class="details">{{ car.year }} · {{ car.mileage }}万公里 · {{ car.transmission }}</p>
          <div class="tags">
            <span v-for="(tag, index) in car.tags" :key="index">{{ tag }}</span>
          </div>
          <div class="description" v-if="viewMode === 'list'">
            <p>{{ car.description }}</p>
          </div>
          <div class="actions">
            <router-link :to="`/car/${car.id}`" class="details-btn">查看详情</router-link>
            <button class="favorite-btn">
              <i class="el-icon-star-off"></i>
            </button>
          </div>
        </div>
      </div>
      
      <!-- 无结果提示 -->
      <div class="no-results" v-if="filteredCars.length === 0">
        <i class="el-icon-warning-outline"></i>
        <h3>未找到符合条件的车辆</h3>
        <p>请尝试调整筛选条件或搜索关键词</p>
        <button @click="resetFilters">重置所有筛选</button>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button :disabled="currentPage === 1" @click="currentPage--">上一页</button>
      <div class="page-numbers">
        <button 
          v-for="page in totalPages" 
          :key="page" 
          :class="{ active: currentPage === page }"
          @click="currentPage = page"
        >{{ page }}</button>
      </div>
      <button :disabled="currentPage === totalPages" @click="currentPage++">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

// 筛选条件
const filters = reactive({
  keyword: '',
  brand: '',
  priceRange: '',
  carType: '',
  age: ''
})

// 视图模式与排序
const viewMode = ref('grid')
const sortOption = ref('default')
const currentPage = ref(1)
const itemsPerPage = 12

// 从URL参数中获取筛选条件
onMounted(() => {
  if (route.query.keyword) {
    filters.keyword = route.query.keyword
  }
  
  if (route.query.category) {
    filters.carType = route.query.category
  }
  
  // 加载车辆数据
  loadCars()
})

// 加载车辆数据（从后端API获取）
async function loadCars() {
  try {
    const response = await axios.get('http://localhost:9999/api/cars')
    allCars.value = response.data.map(car => ({
      id: car.carId || Math.random().toString(36).substr(2, 9), // 如果carId为null，生成一个临时ID
      title: car.title,
      brand: car.brand,
      year: (() => {
        if(car.title!=null){
          // 优先匹配“2023款”中的年份
          const match = car.title.match(/(\d{4})款/);
          if (match) return match[1];

          // 兜底：直接提取4位连续数字
          const yearNum = car.title.match(/\d{4}/)?.[0];
          return yearNum || '未知年份'; // 添加默认值
        }else {
          return '未知年份'
        }

      })(), // 从标题中提取年份
      mileage: car.mileage,
      transmission: car.transmission === 'Automatic' ? '自动' : '手动',
      sellingPrice: car.sellingPrice || 0,
      imgUrl: 'https://via.placeholder.com/300x200', // 暂时使用占位图
      tags: [
        car.brand === '特斯拉' || car.brand === '比亚迪' ? '新能源' : '',
        car.mileage < 10000 ? '准新车' : '',
        car.mileage < 50000 ? '车况良好' : ''
      ].filter(Boolean),
      description: car.description || '暂无描述',
      carType: car.carType
    }))
  } catch (error) {
    console.error('Error fetching cars:', error)
  }
}

// 所有车辆数据（从后端获取）
const allCars = ref([])

// 根据筛选条件和排序方式过滤车辆
const filteredCars = computed(() => {
  let result = [...allCars.value]
  console.log(result)
  // 关键词筛选
  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    result = result.filter(car => 
      car.title.toLowerCase().includes(keyword) || 
      car.brand.toLowerCase().includes(keyword) ||
      car.description.toLowerCase().includes(keyword)
    )
  }
  
  // 品牌筛选
  if (filters.brand) {
    result = result.filter(car => car.brand === filters.brand)
  }
  
  // 价格区间筛选
  if (filters.priceRange) {
    const [min, max] = filters.priceRange.split('-')
    result = result.filter(car => {
      if (max) {
        return car.sellingPrice >= Number(min) && car.sellingPrice < Number(max)
      } else {
        return car.sellingPrice >= Number(min)
      }
    })
  }
  
  // 车型筛选
  if (filters.carType) {
    result = result.filter(car => car.carType === filters.carType)
  }
  
  // 车龄筛选
  if (filters.age) {
    const currentYear = new Date().getFullYear()
    const [min, max] = filters.age.split('-')
    
    result = result.filter(car => {
      const carYear = parseInt(car.year)
      const age = currentYear - carYear
      
      if (max) {
        return age >= Number(min) && age < Number(max)
      } else {
        return age >= Number(min)
      }
    })
  }
  
  // 排序
  switch (sortOption.value) {
    case 'price-asc':
      result.sort((a, b) => a.sellingPrice - b.sellingPrice)
      break
    case 'price-desc':
      result.sort((a, b) => b.sellingPrice - a.sellingPrice)
      break
    case 'year-desc':
      result.sort((a, b) => {
        const yearA = parseInt(a.year)
        const yearB = parseInt(b.year)
        return yearB - yearA
      })
      break
    case 'mileage-asc':
      result.sort((a, b) => a.mileage - b.mileage)
      break
    default:
      // 默认排序，可以是按ID或其他
      break
  }
  console.log(result)
  return result
})

// 分页相关
const totalPages = computed(() => Math.ceil(filteredCars.value.length / itemsPerPage))
const paginatedCars = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage
  const end = start + itemsPerPage
  return filteredCars.value.slice(start, end)
})

// 搜索车辆
function searchCars() {
  currentPage.value = 1 // 重置页码
  
  // 更新URL参数，方便分享和刷新
  router.push({
    query: {
      ...route.query,
      keyword: filters.keyword || undefined
    }
  })
}

// 设置排序选项
function setSortOption(option) {
  sortOption.value = option
}

// 重置所有筛选条件
function resetFilters() {
  Object.keys(filters).forEach(key => {
    filters[key] = ''
  })
  currentPage.value = 1
  sortOption.value = 'default'
  
  // 清除URL参数
  router.push({ path: route.path })
}
</script>

<style lang="scss" scoped>
.cars-container {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  
  h1 {
    font-size: 32px;
    color: #333;
    margin-bottom: 10px;
  }
  
  p {
    color: #666;
    font-size: 16px;
  }
}

.filter-section {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  
  .search-box {
    display: flex;
    margin-bottom: 20px;
    
    input {
      flex: 1;
      padding: 12px;
      border: 1px solid #dcdfe6;
      border-radius: 4px 0 0 4px;
      font-size: 16px;
    }
    
    button {
      padding: 0 25px;
      background-color: #409EFF;
      color: white;
      border: none;
      border-radius: 0 4px 4px 0;
      font-size: 16px;
      cursor: pointer;
      
      &:hover {
        background-color: #66b1ff;
      }
    }
  }
  
  .filters {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: center;
    
    .filter-group {
      display: flex;
      flex-direction: column;
      min-width: 150px;
      
      label {
        margin-bottom: 8px;
        font-weight: bold;
        color: #606266;
      }
      
      select {
        padding: 8px 10px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        background-color: white;
      }
    }
    
    .reset-btn {
      margin-left: auto;
      background-color: #f0f2f5;
      color: #606266;
      border: none;
      padding: 8px 15px;
      border-radius: 4px;
      cursor: pointer;
      align-self: flex-end;
      
      &:hover {
        background-color: #e6e8eb;
      }
    }
  }
}

.sort-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: white;
  border-radius: 8px;
  padding: 10px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  
  span {
    margin-right: 15px;
    color: #606266;
  }
  
  .sort-options {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    
    button {
      background: none;
      border: none;
      padding: 8px 12px;
      cursor: pointer;
      border-radius: 4px;
      color: #606266;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &.active {
        color: #409EFF;
        font-weight: 500;
        background-color: #ecf5ff;
      }
    }
  }
  
  .view-switch {
    margin-left: auto;
    display: flex;
    gap: 5px;
    
    button {
      background: none;
      border: none;
      padding: 8px;
      cursor: pointer;
      border-radius: 4px;
      color: #909399;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &.active {
        color: #409EFF;
        background-color: #ecf5ff;
      }
    }
  }
}

.results-count {
  margin-bottom: 20px;
  color: #606266;
  
  span {
    font-weight: bold;
    color: #409EFF;
  }
}

.car-display {
  display: grid;
  gap: 25px;
  margin-bottom: 30px;
  
  &.view-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    
    .car-card {
      flex-direction: column;
      
      .car-image {
        width: 100%;
        height: 180px;
      }
      
      .car-info {
        width: 100%;
      }
    }
  }
  
  &.view-list {
    grid-template-columns: 1fr;
    
    .car-card {
      flex-direction: row;
      
      .car-image {
        width: 300px;
        height: 200px;
      }
      
      .car-info {
        flex: 1;
        padding: 20px;
      }
    }
  }
  
  .car-card {
    display: flex;
    background-color: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s, box-shadow 0.3s;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
    }
    
    .car-image {
      position: relative;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .price {
        position: absolute;
        bottom: 10px;
        right: 10px;
        background-color: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 5px 10px;
        border-radius: 4px;
        font-weight: bold;
      }
    }
    
    .car-info {
      padding: 15px;
      
      h3 {
        margin: 0 0 10px;
        font-size: 18px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .details {
        color: #666;
        margin-bottom: 10px;
      }
      
      .tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 15px;
        
        span {
          background-color: #f0f7ff;
          color: #409EFF;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
        }
      }
      
      .description {
        margin-bottom: 15px;
        color: #606266;
        line-height: 1.6;
      }
      
      .actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .details-btn {
          background-color: #409EFF;
          color: white;
          text-decoration: none;
          padding: 8px 15px;
          border-radius: 4px;
          flex: 1;
          text-align: center;
          margin-right: 10px;
          
          &:hover {
            background-color: #66b1ff;
          }
        }
        
        .favorite-btn {
          background-color: white;
          border: 1px solid #dcdfe6;
          color: #909399;
          padding: 8px;
          border-radius: 4px;
          cursor: pointer;
          
          &:hover {
            color: #f56c6c;
            border-color: #f56c6c;
          }
        }
      }
    }
  }
  
  .no-results {
    grid-column: 1 / -1;
    text-align: center;
    padding: 60px 20px;
    background-color: white;
    border-radius: 8px;
    
    i {
      font-size: 60px;
      color: #909399;
      margin-bottom: 20px;
    }
    
    h3 {
      font-size: 24px;
      color: #606266;
      margin-bottom: 15px;
    }
    
    p {
      color: #909399;
      margin-bottom: 25px;
    }
    
    button {
      background-color: #409EFF;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      
      &:hover {
        background-color: #66b1ff;
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 30px;
  margin-bottom: 50px;
  
  button {
    background-color: white;
    border: 1px solid #dcdfe6;
    padding: 8px 15px;
    border-radius: 4px;
    cursor: pointer;
    color: #606266;
    
    &:hover:not(:disabled) {
      color: #409EFF;
      border-color: #c6e2ff;
    }
    
    &:disabled {
      cursor: not-allowed;
      color: #c0c4cc;
      background-color: #f4f4f5;
    }
    
    &.active {
      background-color: #409EFF;
      color: white;
      border-color: #409EFF;
    }
  }
  
  .page-numbers {
    display: flex;
    gap: 5px;
  }
}

// Responsive adjustments
@media (max-width: 768px) {
  .car-display.view-list {
    .car-card {
      flex-direction: column;
      
      .car-image {
        width: 100%;
        height: 180px;
      }
    }
  }
  
  .sort-section {
    flex-wrap: wrap;
    
    .view-switch {
      margin-left: 0;
      margin-top: 10px;
      width: 100%;
      justify-content: flex-end;
    }
  }
  
  .filter-section .filters .filter-group {
    min-width: 100%;
  }
}
</style> 